package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.R;
import com.example.domain.entity.User;
import com.example.service.IUserService;
import com.example.until.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 * @author xiaoduan
 * @since 2024-09-24
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    RedisTemplate<Object,Object> redisTemplate;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();

        if(StringUtils.isNotEmpty(phone)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);

            //需要将生成的验证码保存到Session
            // session.setAttribute(phone,code);

            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return R.success("手机验证码短信发送成功");
        }

        return R.error("短信发送失败");
    }

    @PostMapping("/login")
    public R<? extends Object> login(@RequestBody Map<String,String> map, HttpSession session, HttpServletRequest request) {
        String phone = map.get("phone");
        String code = map.get("code");
        // TODO: 2024/9/24 登陆验证
        // session.setAttribute(phone,code);
        String sessionCode = redisTemplate.opsForValue().get(phone).toString();
        // String sessionCode = (String) session.getAttribute(phone);
        if (StringUtils.equals(code, sessionCode) && StringUtils.isNotBlank(sessionCode)) {
            //如果能够比对成功，说明登录成功

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);
            //如果查询不到该用户，就认为是新用户，需要自动完成注册
            if(user == null){
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //将用户ID存入Session中，方便后续的操作
            session.setAttribute("user",user.getId());
            redisTemplate.delete(phone);
            return R.success(user);
        } else {
            return R.error("登陆失败");
        }
    }

    @PostMapping("loginout")
    public R logout(HttpServletRequest request) {
        // 登陆成功 将id存入session中
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}

